<template>
  <div class="editor-container">
    <button class="back-button" @click="goBack">返回</button>
    <h1 class="title">图片编辑器</h1>
    <div v-if="imageSrc" class="canvas-container">
      <canvas ref="canvas" class="canvas"></canvas>
    </div>

    <div class="toolbar">
      <button @click="rotateImage" class="toolbar-button">旋转</button>
      <button @click="toggleCrop" class="toolbar-button">{{ isCropping ? '取消裁剪' : '裁剪' }}</button>
      <button @click="openSaveDialog" class="toolbar-button">保存</button>
      <button @click="toggleDrawing" class="toolbar-button">{{ drawing ? '停止涂鸦' : '开始涂鸦' }}</button>
      <button @click="undo" class="toolbar-button">撤销</button>
    </div>

    <div v-if="isCropping" class="crop-container">
      <h2>裁剪区域</h2>
      <canvas ref="cropCanvas" class="crop-canvas"></canvas>
      <button @click="cropImage" class="toolbar-button">确认裁剪</button>
    </div>

    <div v-if="drawing" class="drawing-area">
      <label for="text-input">输入文本:</label>
      <input type="text" id="text-input" v-model="textInput" @keyup.enter="drawText" />
    </div>



    <!-- 保存对话框 -->
    <div v-if="showSaveDialog" class="save-dialog">
      <h2>保存图片</h2>
      <label for="filename">文件名:</label>
      <input type="text" id="filename" v-model="filename" placeholder="输入文件名" />

      <label for="filetype">文件类型:</label>
      <select v-model="fileType">
        <option value="png">PNG</option>
        <option value="jpeg">JPEG</option>
        <option value="bmp">BMP</option>
        <option value="gif">GIF</option>
      </select>

      <div v-if="fileType === 'jpeg'">
        <label for="quality">图像质量 (0 - 1):</label>
        <input type="number" id="quality" v-model="quality" min="0" max="1" step="0.1" />
      </div>

      <button @click="previewImage" class="toolbar-button">预览</button>
      <button @click="saveImage" class="toolbar-button">确认保存</button>
      <button @click="showSaveDialog = false" class="toolbar-button">取消</button>

      <div v-if="previewSrc" class="preview-container">
        <h3>预览:</h3>
        <img :src="previewSrc" class="preview-image" />
        <p>预计文件大小: {{ estimatedFileSize }} KB</p>
      </div>
    </div>
  </div>
</template>

<script>
import Cropper from "cropperjs";
import "cropperjs/dist/cropper.css";

export default {
  data() {
    return {
      imageSrc: localStorage.getItem('imgUrl'),
      cropper: null,
      drawing: false,
      isCropping: false,
      textInput: "",
      drawingPaths: [],
      currentPath: [],
      operations: [],
      canvasScale: 1,
      showSaveDialog: false,
      filename: "my-image",
      fileType: "png",
      quality: 1, // 默认 JPEG 质量
      previewSrc: null, // 预览图像的 URL
    };
  },
  methods: {
    // 图片上传处理
    inputImg() {
      var url = localStorage.getItem('imgUrl')
      console.log(url)
      if (url) {
        fetch(url)
          .then((response) => {
            if (!response.ok) {
              throw new Error('Network response was not ok');
            }
            return response.blob();
          })
          .then((blob) => {
            const reader = new FileReader();
            reader.onload = (e) => {
              this.imageSrc = e.target.result;
              this.operations.push(this.imageSrc); // 记录操作
              this.$nextTick(() => {
                this.initCanvas();
              });
            };
            reader.readAsDataURL(blob);
          })
          .catch((error) => {
            console.error('There has been a problem with your fetch operation:', error);
          });
      }
    },
    openSaveDialog() {
      this.showSaveDialog = true;
    },
    computed: {
      estimatedFileSize() {
        if (!this.previewSrc) return 0;
        const byteLength = (this.previewSrc.length - 'data:image/png;base64,'.length) * 3 / 4;
        return (byteLength / 1024).toFixed(2); // 转换为 KB
      },
    },
    previewImage() {
      const canvas = this.$refs.canvas;
      this.previewSrc = canvas.toDataURL(`image/${this.fileType}`, this.fileType === 'jpeg' ? this.quality : 1);
    },
    saveImage() {
      const canvas = this.$refs.canvas;
      const link = document.createElement("a");
      link.download = `${this.filename}.${this.fileType}`;
      link.href = canvas.toDataURL(`image/${this.fileType}`, this.fileType === 'jpeg' ? this.quality : 1);
      link.click();
      this.showSaveDialog = false;
      alert("图片已保存！");
    },
    // 初始化画布
    initCanvas() {
      const canvas = this.$refs.canvas;
      const ctx = canvas.getContext("2d");
      const img = new Image();
      img.src = this.imageSrc;

      img.onload = () => {
        canvas.width = img.width;
        canvas.height = img.height;
        ctx.drawImage(img, 0, 0);
        this.canvasScale = 1; // 重置缩放比例
        this.redrawCanvas();
      };
    },
    // 开启/关闭裁剪模式
    toggleCrop() {
      this.isCropping = !this.isCropping;
      if (this.isCropping) {
        this.$nextTick(() => {
          this.showCropCanvas();
        });
      } else {
        if (this.cropper) {
          this.cropper.destroy();
          this.cropper = null;
        }
      }
    },
    // 显示裁剪画布
    showCropCanvas() {
      const cropCanvas = this.$refs.cropCanvas;
      const img = new Image();
      img.src = this.imageSrc;

      img.onload = () => {
        cropCanvas.width = img.width;
        cropCanvas.height = img.height;
        const ctx = cropCanvas.getContext("2d");
        ctx.clearRect(0, 0, cropCanvas.width, cropCanvas.height);
        ctx.drawImage(img, 0, 0);

        // 重新绘制涂鸦路径
        this.redrawPathsOnCanvas(ctx, cropCanvas.width, cropCanvas.height);

        // 初始化 Cropper.js
        this.initCropper(cropCanvas);
      };
    },
    // 初始化 Cropper.js
    initCropper(cropCanvas) {
      this.cropper = new Cropper(cropCanvas, {
        aspectRatio: NaN,
        viewMode: 1,
        autoCropArea: 1,
        responsive: true,
        zoomable: false,
        scalable: false,
      });
    },
    // 确认裁剪
    cropImage() {
      if (this.cropper) {
        const croppedCanvas = this.cropper.getCroppedCanvas();
        this.imageSrc = croppedCanvas.toDataURL();

        const img = new Image();
        img.src = this.imageSrc;

        img.onload = () => {
          const canvas = this.$refs.canvas;
          const ctx = canvas.getContext("2d");

          canvas.width = img.width;
          canvas.height = img.height;
          ctx.clearRect(0, 0, canvas.width, canvas.height);
          ctx.drawImage(img, 0, 0);

          this.redrawCanvas();
        };

        this.toggleCrop();
        this.operations.push(this.imageSrc); // 记录操作
      }
    },
    // 旋转图片
    rotateImage() {
      const canvas = this.$refs.canvas;
      const ctx = canvas.getContext("2d");
      const img = new Image();
      img.src = this.imageSrc;

      img.onload = () => {
        const originalWidth = img.width;
        const originalHeight = img.height;

        canvas.width = originalHeight;
        canvas.height = originalWidth;
        ctx.clearRect(0, 0, canvas.width, canvas.height);
        ctx.save();
        ctx.translate(canvas.width / 2, canvas.height / 2);
        ctx.rotate(Math.PI / 2); // 顺时针旋转 90 度
        ctx.drawImage(img, -originalWidth / 2, -originalHeight / 2);
        ctx.restore();

        this.imageSrc = canvas.toDataURL();
        this.operations.push(this.imageSrc);

        this.drawingPaths = this.drawingPaths.map((path) =>
          path.map((point) =>
            this.rotatePoint(point, canvas.width, canvas.height)
          )
        );

        this.redrawCanvas();
      };
    },
    // 旋转涂鸦点
    rotatePoint(point, canvasWidth, canvasHeight) {
      const angle = Math.PI / 2;
      const cos = Math.cos(angle);
      const sin = Math.sin(angle);

      const centerX = 0.5; // 假设画布中心为 (0.5, 0.5)
      const centerY = 0.5;

      const relativeX = point.x - centerX;
      const relativeY = point.y - centerY;

      const rotatedX = relativeX * cos - relativeY * sin + centerX;
      const rotatedY = relativeX * sin + relativeY * cos + centerY;

      return { x: rotatedX, y: rotatedY };
    },
    // 开启/关闭涂鸦模式
    toggleDrawing() {
      this.drawing = !this.drawing;
      if (this.drawing) {
        this.setupDrawing();
      } else {
        this.cleanupDrawing();
      }
    },
    // 涂鸦设置
    setupDrawing() {
      const canvas = this.$refs.canvas;
      const ctx = canvas.getContext("2d");
      let drawing = false;

      const startDrawing = (event) => {
        drawing = true;
        this.currentPath = [];
        ctx.beginPath();
      };

      const draw = (event) => {
        if (drawing) {
          const rect = canvas.getBoundingClientRect();
          const x = (event.clientX - rect.left) / rect.width;
          const y = (event.clientY - rect.top) / rect.height;

          ctx.lineWidth = 5;
          ctx.lineCap = "round";
          ctx.strokeStyle = "red";
          ctx.lineTo(x * canvas.width, y * canvas.height);
          ctx.stroke();

          this.currentPath.push({ x, y });
        }
      };

      const stopDrawing = () => {
        drawing = false;
        ctx.closePath();
        if (this.currentPath.length > 0) {
          this.drawingPaths.push(this.currentPath);
          this.currentPath = [];
          this.operations.push(this.imageSrc);
        }
      };

      canvas.addEventListener("mousedown", startDrawing);
      canvas.addEventListener("mousemove", draw);
      canvas.addEventListener("mouseup", stopDrawing);
      canvas.addEventListener("mouseout", stopDrawing);

      this.drawingEvents = { startDrawing, draw, stopDrawing };
    },
    // 清理涂鸦
    cleanupDrawing() {
      const canvas = this.$refs.canvas;

      canvas.removeEventListener("mousedown", this.drawingEvents.startDrawing);
      canvas.removeEventListener("mousemove", this.drawingEvents.draw);
      canvas.removeEventListener("mouseup", this.drawingEvents.stopDrawing);
      canvas.removeEventListener("mouseout", this.drawingEvents.stopDrawing);

      this.currentPath = [];
    },
    // 撤销操作
    undo() {
      if (this.drawingPaths.length > 0) {
        this.drawingPaths.pop();
        this.redrawCanvas();
      } else if (this.operations.length > 1) {
        this.operations.pop();
        this.imageSrc = this.operations[this.operations.length - 1];
        this.initCanvas();
      }
    },
    // 重新绘制画布
    redrawCanvas() {
      const canvas = this.$refs.canvas;
      const ctx = canvas.getContext("2d");
      const img = new Image();
      img.src = this.imageSrc;

      img.onload = () => {
        ctx.clearRect(0, 0, canvas.width, canvas.height);
        ctx.drawImage(img, 0, 0);

        // 重新绘制涂鸦路径
        this.redrawPathsOnCanvas(ctx, canvas.width, canvas.height);
      };
    },
    // 在画布上重新绘制涂鸦路径
    redrawPathsOnCanvas(ctx, canvasWidth, canvasHeight) {
      for (const path of this.drawingPaths) {
        ctx.beginPath();
        ctx.lineWidth = 5;
        ctx.lineCap = "round";
        ctx.strokeStyle = "red";
        ctx.moveTo(path[0].x * canvasWidth, path[0].y * canvasHeight);
        for (const point of path) {
          ctx.lineTo(point.x * canvasWidth, point.y * canvasHeight);
        }
        ctx.stroke();
        ctx.closePath();
      }
    },
    // 文本输入
    drawText() {
      const canvas = this.$refs.canvas;
      const ctx = canvas.getContext("2d");
      ctx.font = "30px Arial";
      ctx.fillStyle = "blue";
      ctx.fillText(this.textInput, 50, 50);
      this.textInput = "";
    },
    // 窗口大小变更时处理
    handleResize() {
      if (this.cropper) {
        this.cropper.resize();
      }
    },
    goBack() {
      // 在这里实现返回逻辑，比如导航到上一页或指定路径
      window.history.back();
    },
  },
  mounted() {
    window.addEventListener("resize", this.handleResize);
    this.inputImg()
  },
  beforeDestroy() {
    if (this.cropper) {
      this.cropper.destroy();
    }
    window.removeEventListener("resize", this.handleResize);
  },
};
</script>

<style scoped>
.editor-container {
  position: relative;
  max-width: 800px;
  margin: 20px auto;
  padding: 20px;
  border: 1px solid #ddd;
  border-radius: 8px;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
  text-align: center;
  background-color: #f9f9f9;
}
.editor-container .back-button {
  position: absolute;
  top: 10px;
  left: 10px;
  padding: 8px 12px;
  font-size: 14px;
  color: white;
  background-color: #007bff;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  transition: background-color 0.3s;
}

.back-button:hover {
  background-color: #0056b3;
}
.title {
  font-size: 24px;
  margin-bottom: 20px;
}

.file-input {
  margin-bottom: 20px;
  padding: 10px;
}

.canvas-container,
.crop-container {
  position: relative;
}

.canvas {
  max-width: 100%;
  border: 1px solid #ccc;
  border-radius: 4px;
}

.crop-container {
  width: 100%;
  max-width: 800px;
  margin: 0 auto;
}

.crop-canvas {
  width: 100%;
  height: auto;
  border: 1px solid #ccc;
  border-radius: 4px;
}

.toolbar {
  margin: 20px 0;
}

.toolbar-button {
  padding: 10px 15px;
  margin: 0 5px;
  border: none;
  border-radius: 4px;
  background-color: #007bff;
  color: white;
  font-size: 16px;
  cursor: pointer;
  transition: background-color 0.3s;
}

.toolbar-button:hover {
  background-color: #0056b3;
}

.drawing-area {
  margin-top: 20px;
}

.save-dialog {
  margin: 20px 0;
}

.preview-container {
  margin-top: 20px;
}

.preview-image {
  max-width: 100%;
  border: 1px solid #ccc;
  border-radius: 4px;
}
</style>